package hr.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import hr.entity.EmployeeDepartForm;
import hr.entity.EmployeeOnboardingLink;
import hr.entity.Employee;
import hr.entity.vo.FormInline;
import hr.entity.vo.LoginVo;
import hr.entity.vo.ObtainDepartment;
import hr.entity.vo.Paging;
import hr.entity.vo.request.DepartureInfoVO;
import hr.entity.vo.response.EntryStatusVo;
import hr.service.EmployeesService;
import hr.utils.CommonUtils;
import hr.utils.Result.R;
import hr.utils.Result.Result;
import hr.utils.Result.ResultUtil;
import hr.utils.TokenUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 员工信息表 前端控制器
 * </p>
 *
 * @author zzh
 * @since 2023-12-04
 */
@Tag(name = "员工管理")
@RestController
@Slf4j
@RequestMapping("/employees")
public class EmployeesController {
    @Autowired
    private EmployeesService employeesService;

    @Autowired
    private TokenUtils tokenUtils;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 登录
     *
     * @param paramMap
     * @return
     * @since 2023年12月19日18:20:41
     */
    @Operation(summary = "登录")
    @PostMapping("/login")
    public R login(@RequestBody LoginVo paramMap) throws Exception {
        // 登录
        Employee employee = employeesService.login(paramMap);
        // 根据employeeId和name生成token字符串，通过map返回
        String token;
        if (employee.getName().equals("yk")) {
            // 临时token 有效期三十分钟
            token = tokenUtils.createToken(employee);
        } else {
            token = tokenUtils.createToken(String.valueOf(employee.getEmployeeId()));
        }
        return R.success().addKeyValueToData("employee", employee).addKeyValueToData("token", token);
    }

    /**
     * 退出
     *
     * @param request
     * @return
     */
    @Operation(summary = "退出")
    @PostMapping("/logout")
    public Result<Object> logout(HttpServletRequest request) {
        String token = CommonUtils.getTokenFromReqHeaders(request);
        String key = tokenUtils.getKey(token);
        log.info("退出用户：{}", key);
        return Boolean.TRUE.equals(stringRedisTemplate.delete(key)) ?
                ResultUtil.success("退出成功") :
                ResultUtil.error("系统异常，稍后再试");

    }

    @Operation(summary = "删除员工")
    @PostMapping("/employees/{employeeId}")
    public Result<Object> deleteEmployees(@PathVariable("employeeId") Integer employeeId) {
        return employeesService.removeById(employeeId) ?
                ResultUtil.success("删除成功") :
                ResultUtil.error("删除失败");
    }

    @Operation(summary = "模糊查询(员工名称)")
    @PostMapping("/searchByEmployeeName/{name}")
    public Result<Object> searchByEmployeeName(@PathVariable("name") String employeeName) {
        List<Employee> employeeList = employeesService.searchByEmployeeName(employeeName);
        HashMap<String, Object> map = new HashMap<>();
        map.put("employeesList", employeeList);
        return ResultUtil.success(map);
    }

    @Operation(summary = "获取员工列表")
    @PostMapping("/getAllEmployees")
    public Result<Object> getAllEmployees(@RequestBody ObtainDepartment obtainDepartment) throws Exception {

        List<?> list = employeesService.selectAllDepartments(obtainDepartment);
        HashMap<String, Object> map = new HashMap<>();
        map.put("allEmployeeList", list);
        map.put("page", obtainDepartment);

        return ResultUtil.success(map);
    }


    /**
     * 生成邀约链接
     *
     * @param request
     * @return
     * @throws Exception
     * @author 柳继纪
     * @time 2023年12月16日17:10:58
     */
    @Operation(summary = "生成邀约链接")
    @PostMapping("/fillInOnboardingRegistrationInformation")
    public R fillInOnboardingRegistrationInformation(HttpServletRequest request) throws Exception {
        // 获取登录人的id TODO
//        String loginId = TokenUtils.getKey(CommonUtils.getTokenFromReqHeaders(request));
        long loginId = 0L;
        Map<String, String> map = employeesService.fillInOnboardingRegistrationInformation(loginId);
        return map != null ?
                R.success(map) :
                R.error().setMessage("系统错误");
    }

    /**
     * 收集入职报道信息填写的数据
     *
     * @param form
     * @return
     */
    @Operation(summary = "收集入职报道信息填写的数据")
    @PostMapping("collectOnboardingReportsAndReports")
    public Result<Object> collectOnboardingReportsAndReports(@RequestBody FormInline form) throws Exception {
        log.info("{}", form);
        boolean addFlag = employeesService.collectOnboardingReportsAndReports(form);
        return ResultUtil.success();
    }


    /**
     * 查看入职链接填写情况
     *
     * @return
     */
    @Operation(summary = "查看入职链接填写情况")
    @PostMapping("viewTheStatusOfFillingOutTheOnboardingLink")
    public Result<?> viewTheStatusOfFillingOutTheOnboardingLink(@RequestBody Paging page) {
        List<EntryStatusVo> list = employeesService.findStateFillLink(page);
        HashMap<String, Object> map = new HashMap<>();
        map.put("list", list);
        map.put("page", page);
        return ResultUtil.success(map);
    }

    /**
     * 失效一个链接
     *
     * @param vo
     * @return
     * @author 柳继纪
     * @since 2023年12月16日21:39:10
     */
    @Operation(summary = "失效邀约链接")
    @PostMapping("brokenLink")
    public Result<?> brokenLink(@RequestBody EmployeeOnboardingLink vo) throws Exception {
        int rows = employeesService.brokenLink(vo);
        return rows == 0 ? ResultUtil.fail() : ResultUtil.success();
    }

    /**
     * 查看入职表单填写
     *
     * @param map 链接id
     * @return
     * @author 柳继纪
     * @since 2023年12月17日17:04:57
     */
    @Operation(summary = "查看入职表单填写")
    @PostMapping("viewOnboardingForm")
    public Result<?> viewOnboardingForm(@RequestBody Map<String, String> map) throws Exception {
        FormInline formInline = employeesService.viewOnboardingForm(map.get("urlId"));
        return formInline == null ? ResultUtil.fail() : ResultUtil.success(formInline);
    }


    /**
     * 查看员工详细信息
     *
     * @param map 员工id
     * @return
     * @author 柳继纪
     * @since 2023年12月17日20:29:57
     */
    @Operation(summary = "查看员工详细信息")
    @PostMapping("viewEmployeeDetails")
    public Result<?> viewEmployeeDetails(@RequestBody Map<String, String> map) throws Exception {
        FormInline formInline = employeesService.viewEmployeeDetails(map.get("empId"));
        return formInline == null ? ResultUtil.fail() : ResultUtil.success(formInline);
    }

    /**
     * 查看员工详细信息
     *
     * @param form 表单
     * @return
     * @author 柳继纪
     * @since 2023年12月17日20:59:46
     */
    @Operation(summary = "修改员工详细信息")
    @PostMapping("updateEmployeeDetails")
    public Result<?> updateEmployeeDetails(@RequestBody FormInline form) throws Exception {
        boolean updateResult = employeesService.updateEmployeeDetails(form);
        return !updateResult ? ResultUtil.fail() : ResultUtil.success();
    }

    /**
     * 处理入职表单填写
     *
     * @param map 表单填写id 和 handleMethod：处理方式 reject：驳回 agree：同意
     * @return
     * @author 柳继纪
     * @since 2023年12月17日17:04:52
     */
    @Operation(summary = "处理入职表单填写")
    @PostMapping("handleFormSubmission")
    public Result<?> handleFormSubmission(@RequestBody Map<String, String> map) throws Exception {
        boolean handleFlag = employeesService.handleFormSubmission(map.get("formId"), map.get("handleMethod"));
        return handleFlag ? ResultUtil.success():ResultUtil.fail();
    }

    @Operation(summary = "员工离职申请")
    @PostMapping("resignationApplication")
    public R resignationApplication() throws Exception {
        String url = employeesService.resignationApplication();
        return url == null ? R.error() : R.success().addKeyValueToData("url", url);
    }

    @Operation(summary = "提交离职申请表")
    @PostMapping("submitResignationApplicationForm")
    public R submitResignationApplicationForm(@RequestBody DepartureInfoVO vo) {
        boolean add = employeesService.submitResignationApplicationForm(vo);
        return add ? R.error() : R.success();
    }

    @Operation(summary = "获取离职申请列表")
    @PostMapping("getResignationApplicationForm")
    public R getResignationApplicationForm(@RequestBody ObtainDepartment obtainDepartment) {
        IPage<?> iPage = employeesService.getResignationApplicationForm(obtainDepartment);

        return iPage == null ? R.error() : R.success(iPage);
    }

    @Operation(summary = "手动同意离职")
    @PostMapping("agreeDepart")
    public R agreeDepart(@RequestBody EmployeeDepartForm vo) {
        return employeesService.agreeDepart(vo) ? R.success() : R.error();
    }

    @Operation(summary = "查看员工性别、婚姻比例（报表）")
    @PostMapping("/getEmployeeRatio")
    public R getEmployeeRatio() {
        Map<String, Object> map = employeesService.getEmployeeRatio();
        return R.success(map);
    }
    @Operation(summary = "近七天员工入职离职分析")
    @PostMapping("/AnalysisOfEmployeeOnboardingAndResignationInThePastSevenDays")
    public R AnalysisOfEmployeeOnboardingAndResignationInThePastSevenDays() {
        Map<String, Object> map = employeesService.HandleSevenDayInAndLeave();
        return R.success(map);
    }

}

